package com.example.exception;

import com.example.enums.CodeEnum;
import com.example.utils.R;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.UnexpectedTypeException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 王鹤蒲
 * @Date 2023 08 06
 */

@RestControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public R handleServiceException(ServiceException e){
        return R.error(e.getCode(),e.getMessage());
    }

    @ExceptionHandler(JwtAuthenticationException.class)
    @ResponseBody
    public R handleJwtAuthenticationException(JwtAuthenticationException jwtAuthenticationException){
        return R.error(CodeEnum.NEED_LOGIN.getCode(), jwtAuthenticationException.getMessage());
    }


    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public R handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        BindingResult bindingResult=e.getBindingResult();
       String defaultMessage=bindingResult.getFieldError().getDefaultMessage();
       String code=bindingResult.getFieldError().getCode();
     return  R.error(CodeEnum.VALIDATE_ERROR.getCode(), defaultMessage);
    }

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public R handleBindingException(BindException e){
        BindingResult bindingResult=e.getBindingResult();
        List<FieldError> fieldErrors=bindingResult.getFieldErrors();
        Map<String,Object> errorMessages=new HashMap<>();
        fieldErrors.forEach(o->errorMessages.put(o.getField(),o.getDefaultMessage()));
        return  R.error(CodeEnum.VALIDATE_ERROR.getCode(),errorMessages);
    }

    @ExceptionHandler(UnexpectedTypeException.class)
    @ResponseBody
    public R handleUnexpectedTypeException(UnexpectedTypeException e){
       return R.error(CodeEnum.VALIDATE_ERROR.getCode(),e.getMessage());
    }
}
